package com.heima.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
public class UploadController {

    @RequestMapping("/upload")
    public void upload(MultipartFile file, HttpServletRequest request) {
        //1.获取文件的类型
        //获取原始文件名
        String filename = file.getOriginalFilename();
        //获取文件后缀
        int i = filename.lastIndexOf(".");
        //截取后缀名
        String hou = filename.substring(i);
        System.out.println("文件的后缀是：" + hou);
        //2.生成唯一的文件名称
        String uuid = UUID.randomUUID().toString().replace("-", "");
        //3.动态获取 服务器所在的路径
        String realPath = request.getSession().getServletContext().getRealPath("/image");
        File filePath = new File(realPath);
        //如果image文件夹或者中间的文件夹不存在，那么就创建出来
        if (!filePath.exists()) {
            filePath.mkdirs();
        }
        System.out.println(realPath + File.separator + uuid + hou);
        //开始上传
        try {
            file.transferTo(new File(realPath + File.separator + uuid + hou));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
